import pandas as pd
import numpy as np
import chardet #检测字符集编码（charater detect）
import time

data = pd.read_csv('某公司衍生数据.csv', sep=',', encoding='ascii') #设置字符编码是ascii, 用记事本打开该csv文件看到它的分隔符是逗号，因此设置sep=','
pb = np.array(data['PB']) #市净率PB = 每股市价/每股净资产
pe = np.array(data['PE']) #市盈率PE = 每股市价/每股税后利润
ps = np.array(data['PS'])

new_data = data.dropna()
pcf = np.array(new_data['PCF'])

L = [pb, pe, ps, pcf]
L_names = ['pb', 'pe', 'ps', 'pcf']
ask = [0.66,6.82,0.17,2.84]


def print_percentiles(Name):
    percentiles = [10,30,50,70,90]
    ptiles_vers = np.percentile(Name, percentiles)
    Max = np.max(Name)
    Mean = np.mean(Name)
    Std = np.std(Name)
    for item in ptiles_vers:
        print(round(item,2), sep = '\t', end = '\t')
    print(round(Max,2), round(Mean,2), round(Std,2), sep = '\t', end = '\n')

def get_percentiles(Name, x):
    l = 0
    r = 1
    mid = 0
    while True:
        mid = (l + r) / 2
        if np.percentile(Name, 100*mid) >= x:
            r = mid
        elif np.percentile(Name, 100*mid) < x:
            l = mid 
        if np.abs(r - l) <= 0.001:
            break
    return mid

# Print the percentiles 

print("The percentiles asked show below")

for i in range(0,4):
    print(L_names[i], end = '\t')
    print_percentiles(L[i])

for i in range(0,4):
    print(L_names[i],end = '\t')
    print(L[i].min())

print("")
print("")
print("The percentiles of the numbers given show below")


ans = []
for i in range(0, 4):
    print(L_names[i], end = '\t')
    ans.append(round(get_percentiles(L[i], ask[i]),2)* 100)
    print(ans[i])

per_Mean = np.array(ans).mean()

print("")
print("")
print("The average value of the four given numbers shows below")
print(per_Mean)

roe = pb / pe
ask_roe = ask[0] / ask[1]

ans.append(round(get_percentiles(roe, ask_roe), 2) * 100)

print("")
print("")
print("The percentile of the ROE shows below")
print(ans[-1])


